package com.hmall.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.client.ItemClient;
import com.hmall.common.client.UserClient;
import com.hmall.common.dto.Address;
import com.hmall.common.dto.Item;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderLogistics;
import com.hmall.order.pojo.RequestParams;
import com.hmall.order.service.IOrderService;
import com.hmall.order.utils.UserHolder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class OrderService extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    @Autowired
    private ItemClient itemClient;
    @Autowired
    private UserClient userClient;
    @Autowired
    private OrderLogisticsService logisticsService;
    @Transactional
    //创建订单
    @Override
    public Long createOrder(RequestParams requestParams) {
        //1、根据雪花算法生成订单id
        //2、提供的FeignClient，实现根据商品id查询商品接口
        Item itemId = itemClient.queryItemById(requestParams.getItemId());
        //3、获取总金额 ：商品价格 * 前端传来的num个数
        long total = itemId.getPrice() * requestParams.getNum();
        //4、封装order对象信息
        Order order = new Order();
        order.setTotalFee(total);
        order.setPaymentType(requestParams.getPaymentType());
        order.setUserId(UserHolder.getUser());
        order.setStatus(1);
        //5、将order写入数据库tb_Order表中
        this.save(order);

        //6、user-service的根据id查询地址接口封装为FeignClient
        Long addressId = requestParams.getAddressId();
        //7、根据addressId 获取地址信息
        Address address = userClient.findAddressById(addressId);
        //8、将地址封装 成orderLogistics物流对象，写入tb_order_logistics表
        OrderLogistics orderLogistics = new OrderLogistics();
        BeanUtils.copyProperties(address,orderLogistics);
        orderLogistics.setOrderId(order.getId());
        logisticsService.save(orderLogistics);

        //9、扣减库存
        itemClient.updateStock(requestParams.getItemId(),requestParams.getNum());
        return order.getId();
    }
}
